package com.gitee.huanminabc.utils_tools.config_refresh.core;

import com.gitee.huanminabc.jcommon.base.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;


/**
 * 程序运行时候动态刷新配置
 * 目前只支持yml配置文件, 并且不支持太复杂的配置 支持占位符${} 和#{}   不支持yml中的list配置
 * 获取配置方式支持: @Value注解,  Environment   ,不支持@ConfigurationProperties自动绑定
 * 支持配置路径(打包后的):
 * 1. jar同级目录
 * 2. jar同级config目录
 * 支持配置路径(未打包源码):
 * 1. 最顶层root目录(多模块也一样)
 * 2. 最顶层root目录下的config目录(多模块也一样)
 */
@Component
@Slf4j
@DependsOn("springContextUtil")
public class ConfigRealTime{
    @Autowired
    private List<ChangeConfigHandler> changeConfigHandlerList;
    @Value("${config.refresh.enable:false}")
    private boolean enable;
    @Value("${config.refresh.time:100000}")
    private long time; //刷新时间间隔,默认100秒

    @PostConstruct
    public void refresh() {
        new  Thread(()->{
            while (enable){
                log.debug("++++++++++++++++++++++配置刷新定时任务开始执行++++++++++++++++++++++:{}", DateUtil.now());
                for (ChangeConfigHandler changeConfigHandler : changeConfigHandlerList) {
                    try {
                        changeConfigHandler.refresh();
                    } catch (Exception e) {
                        log.error("刷新配置失败:", e);
                    }
                }
                log.debug("++++++++++++++++++++++配置刷新定时任务执行结束++++++++++++++++++++++:{}", DateUtil.now());
                try {
                    Thread.sleep(time);//100秒刷新一次
                } catch (InterruptedException e) {
                    log.error("刷新配置失败:", e);
                }
            }
        }).start();

    }
}
